package cn.rui.controller;

import cn.rui.constant.MessageConstant;
import cn.rui.entity.PageResult;
import cn.rui.entity.QueryPageBean;
import cn.rui.entity.Result;
import cn.rui.pojo.Menu;
import cn.rui.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 徽州大都督
 * @date 2020/8/30
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;  //加密

    /**
     * 登陆跳转
     *
     * @return
     */
    @RequestMapping("login")
    public String login() {

        return "redirect:http://localhost:82/main.html";
    }

    /**
     * 获取当前登陆用户名
     *
     * @return
     */
    @GetMapping("getUsername")
    @ResponseBody
    public Result getUserName() {
        try {
            User principal = (User) SecurityContextHolder.getContext ().getAuthentication ().getPrincipal ();

            String username = principal.getUsername ();
            return new Result (true, MessageConstant.GET_USERNAME_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result (false, MessageConstant.GET_USERNAME_FAIL);
        }

    }

    /**
     * 根据当前登陆用户名查询显示的菜单选项
     */
    @GetMapping("showMenu")
    @ResponseBody
    public Result showMenu() {

        //获取当前登陆用户名
        User principal = (User) SecurityContextHolder.getContext ().getAuthentication ().getPrincipal ();
        String username = principal.getUsername ();
        cn.rui.pojo.User user = userService.findByUsername (username);
        try {
            List<Menu> menuList = userService.findMenuByUsername (user);

            return new Result (true, MessageConstant.GET_USERNAME_SUCCESS, menuList);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result (false, MessageConstant.SYSTEM_ERROR);
        }
    }

    /**
     * 设置登陆超时返回提示信息
     *
     * @return
     */
    @GetMapping("sessionTimeOut")
    @ResponseBody
    public String sessionTimeOut() {

        return "登陆超时，请重新登录!";
    }

    /**
     * 分页查询用户
     */
    @PostMapping("findPage")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('USER_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        PageResult page = userService.findPage (queryPageBean);

        return page;
    }

    @GetMapping("findById/{id}")
    @ResponseBody
    public Result findById(@PathVariable("id") Integer id) {

        try {
            Map map = userService.findById (id);
            return new Result (true, MessageConstant.EDIT_MENU_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result (false, MessageConstant.SYSTEM_ERROR);
        }


    }

    @PostMapping("edit/{roleName}")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority('USER_EDIT')")
    public Result edit(@PathVariable("roleName") String roleName, @RequestBody Map map) {

        //用户名
        String username = map.get ("username").toString ();
        //查询用户比较当前密码是否相同
        cn.rui.pojo.User user = userService.findByUsername (username);
        if (!user.getPassword ().equalsIgnoreCase (map.get ("password").toString ())){
            map.put ("password", passwordEncoder.encode (map.get ("password").toString ()));
        }

        try {
            userService.edit (roleName, map);
            return new Result (true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result (true, MessageConstant.EDIT_USER_FAIL);
        }

    }

    /**
     * 修改登陆密码
     * @param username
     * @param password
     * @return
     */
    @PostMapping("updatePassword/{username}/{password}")
    @ResponseBody
    public Result updatePassword(@PathVariable("username")String username,@PathVariable("password")String password){

        String encodePassword = passwordEncoder.encode (password); //加密后的密码
        try {
            userService.updatePassword(username,encodePassword);
            return new Result (true,MessageConstant.EDIT_PASSWORD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result (false,MessageConstant.EDIT_PASSWORD_FAIL);
        }
    }
}
